package com.hzy.framework;

import com.hzy.toolkit.Tools;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 解决 Request body 信息无法重复读取问题
 *
 * 参考地址：https://blog.csdn.net/weixin_44560245/article/details/90700720
 *
 * @author hzy
 */
// @Slf4j
public class HttpRequestWrapper extends HttpServletRequestWrapper {

  private final byte[] body;

  public HttpRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException {
    super(request);
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    body = Tools.getBodyString(request).getBytes("UTF-8");
  }

  @Override
  public BufferedReader getReader() throws IOException {
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {

    final ByteArrayInputStream bais = new ByteArrayInputStream(body);

    return new ServletInputStream() {
      @Override
      public int read() throws IOException {
        return bais.read();
      }

      @Override
      public boolean isFinished() {
        return false;
      }

      @Override
      public boolean isReady() {
        return false;
      }

      @Override
      public void setReadListener(ReadListener readListener) {
      }
    };
  }
}